# -*-coding: utf-8 -*-
"""
    @Theme   : 处理 index 页面请求的 API
    @Time    : 2024/6/9 10:32
    @Author  : YamFish
    @Url     : https://www.zhihu.com/people/yamfish
"""
from flask import render_template, request, jsonify

from . import app, db
from .utils import check_integrity, check_update, check_fields, transfer_id


@app.route('/')
def index():
    data_list = db.query_info()
    return render_template('index.html', data_list=data_list)


@app.route('/add', methods=['POST'])
def add_info():
    info = request.json

    if fail := check_integrity(info):
        return jsonify({'success': False, 'reason': fail})

    if fail := check_fields(info):
        return jsonify({'success': False, 'reason': fail})

    info['deleted'] = 0
    insert_result = db.add_info(info)

    return jsonify({'success': insert_result})


@app.route('/update', methods=['POST'])
def update_info():
    info = request.json

    if fail := check_update(info):
        return jsonify({'success': False, 'reason': fail})

    people_id = transfer_id(info['people_id'])
    if people_id == -1:
        return jsonify({'success': False, 'reason': 'ID必需为数字'})

    if fail := check_fields(info['updated_info']):
        return jsonify({'success': False, 'reason': fail})

    update_result = db.update_info(people_id, info['updated_info'])
    return jsonify({'success': update_result})


@app.route('/delete/<people_id>', methods=['GET'])
def delete(people_id):
    people_id = transfer_id(people_id)
    if people_id == -1:
        return jsonify({'success': False, 'reason': 'ID必需为数字'})

    delete_result = db.del_info(people_id)
    return jsonify({'success': delete_result})
